'use strict';
const crypto = require('crypto');
const createConfig = require('uni-config-center');
const shareConfig = createConfig({
	pluginId: 'uni-id'
})
// let customPassword = {}
// if (shareConfig.hasFile('custom-password.js')) {
// 	customPassword = shareConfig.requireFile('custom-password.js') || {}
// }
exports.main = async (event, context) => {
	// password-未加密密码  userPassword - 用户加密密码
	const { password, userPassword } = event;
	//初始化比对逻辑
	const passwordAlgorithmMap = {
		UNI_ID_HMAC_SHA1: 'hmac-sha1',
		UNI_ID_HMAC_SHA256: 'hmac-sha256',
		UNI_ID_CUSTOM: 'custom'
	}
	const passwordAlgorithmKeyMap = Object.keys(passwordAlgorithmMap).reduce((res, item) => {
		res[passwordAlgorithmMap[item]] = item
		return res
	}, {});
	const version = 1; //配置文件中版本号
	//验证密码逻辑
	const [algorithmKey = '', cost = 0, hashStr = ''] = userPassword.split('$').filter(key => key)
	const algorithm = passwordAlgorithmMap[algorithmKey] ? passwordAlgorithmMap[algorithmKey].substring(5) : null
	const salt = hashStr.substring(0, Number(cost))
	const hash = hashStr.substring(Number(cost))
	const passwordHash = crypto.createHmac(algorithm, salt).update(password).digest('hex')
	return {
		isTrue: passwordHash === hash
	}
}